#include "label.h"

/*******************************************************
					generator
*******************************************************/

labels::generator::generator(short s, short p, const char* path){
	space = s;
	padding = p;

	//read all necessary data
	char new_path[255];
	char filename[6] = "x.png";

	//letters
	for(int i=0 ;i<24 ; i++){
		strcpy(new_path, path);
		filename[0] = i+97;
		strcat(new_path, filename);
		printf("Loading font file: %s\n",new_path);
		lower_case[i] = IMG_Load(new_path);
		if(lower_case[i] == NULL){
			printf("ERROR\n");
		}
		
		strcpy(new_path, path);
		filename[0] = i+65;
		strcat(new_path, filename);
		printf("Loading font file: %s\n",new_path);
		upper_case[i] = IMG_Load(new_path);
		if(upper_case[i] == NULL){
			printf("ERROR\n");
		}
	}

	//digits
	for(int i=0 ; i<10 ; i++){
		strcpy(new_path, path);
		filename[0] = i+48;
		strcat(new_path, filename);
		printf("Loading font file: %s\n",new_path);
		digits[i] = IMG_Load(new_path);
		if(digits[i] == NULL){
			printf("ERROR\n");
		}

	}
}

labels::generator::~generator(){
	//delete char surfaces
	for(int i=0 ; i<24 ; i++){
		delete upper_case[i];
		delete lower_case[i];
	}

	for(int i=0; i<10 ; i++){
		delete digits[i];
	}
}

SDL_Surface* labels::generator::get_char_surface(char c){
	if(c <= '9'){
		//digit
		return digits[c-48];
	}
	else if(c <= 'Z'){
		//uppercase letter
		return upper_case[c-65];
	}
	else{
		//lowercase letter
		return lower_case[c-97];
	}
}

short labels::generator::get_width(const char* caption){
	int w = 0;
	int i = 0;
	while(caption[i] != '\0'){
		if(caption[i] != 32){
			w += get_char_surface(caption[i])->w;
			w += padding;
		}
		else{
			//space
			w += padding + space;
		}
		i++;
	}
	w -= padding;

	return w;
}

short labels::generator::get_height(const char* caption){
	int h = 0;
	int i = 0;
	while(caption[i] != '\0'){
		if(caption[i] != 32){
			h = std::max(h,get_char_surface(caption[i])->h);
		}
		i++;
	}
	return h;
}

//and finally...

void labels::generator::draw(const char* capt, short x, short y, SDL_Surface* target){
	int i = 0;
	SDL_Rect dest;
	dest.x = x;
	dest.y = y;
	SDL_Surface *letter;
	while(capt[i] != '\0'){
		if(capt[i] == 32){
			//space
			dest.x += padding + space;
		}
		else{
			letter = get_char_surface(capt[i]);
			//copy letter noto target surface
			SDL_BlitSurface(letter, NULL, target, &dest);
			dest.x += padding + letter->w;
		}
		i++;
	}
}

/**************************************************************
						label
*************************************************************/

labels::label::label(const char* capt, generator *g){
	strcpy(caption, capt);	
	gen = g;
}

void labels::label::draw(SDL_Surface* target, short x, short y){
	gen->draw(caption, x, y, target);
}

short labels::label::get_height(){
	return gen->get_height(caption);
}

short labels::label::get_width(){
	return gen->get_width(caption);
}
